package ru.spb.xmlreshelper.screen;

import com.google.common.eventbus.Subscribe;
import ru.spb.xmlreshelper.domain.ICdtService;
import ru.spb.xmlreshelper.gui.PanelEvent;
import ru.spb.xmlreshelper.screen.cdt.CDTSelectionEvent;
import ru.spb.xmlreshelper.screen.cdt.CDTViewPanel;
import ru.spb.xmlreshelper.screen.database.DatabaseConnectionPanel;
import ru.spb.xmlreshelper.screen.files.XmlXslSelectionPanel;
import ru.spb.xmlreshelper.util.GuiUtils;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

/**
 * @author Nikita.Brazhnikov
 */
public class RootWindow {

	private static final String title = "XSL/HTML upload helper";
	private JFrame window;

	static {
		GuiUtils.setUpLaF();
	}

    private JTabbedPane tabbedPane;

    protected RootWindow() {
		window = createFrame();
		setUpComponents();
        GuiUtils.getEventBus().register(this);
	}

	public static RootWindow openWindow() {
		final RootWindow window = new RootWindow();
		window.showWindow();
		return window;
	}

	protected void showWindow() {
		GuiUtils.centerFrame(window);
		window.setVisible(true);
	}

	private JFrame createFrame() {
		final JFrame frame = new JFrame(title);
		frame.setPreferredSize(new Dimension(800, 600));
		frame.setMinimumSize(new Dimension(800, 600));
		frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
		WindowListener exitListener = new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				frame.setVisible(false);
				super.windowClosing(e);
			}
		};
		frame.addWindowListener(exitListener);
		return frame;
	}


	protected void setUpComponents() {
		window.getRootPane().setLayout(new BorderLayout());
		window.getRootPane().add(new DatabaseConnectionPanel(), BorderLayout.NORTH);

        tabbedPane = new JTabbedPane(JTabbedPane.TOP);
		tabbedPane.add("Files", new XmlXslSelectionPanel());
		tabbedPane.add("CDT", new CDTViewPanel());
		window.getRootPane().add(tabbedPane, BorderLayout.CENTER);

		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				window.repaint();
			}
		});
	}

    @Subscribe
    public void handlePanelEvent(PanelEvent event) {
        String eventName = event.getEventName();
        if (eventName.equals(ICdtService.CDT_LIST_UPDATED)) {
            tabbedPane.setSelectedIndex(1);
        }
    }

    @Subscribe
    public void handleCdtSelectionEvent(CDTSelectionEvent event) {
        if (event.isDoubleClick())
            tabbedPane.setSelectedIndex(0);

    }
}
